<template>
	<view class="all">
		<view class="operate">
			<view class="type">
				<uni-data-select v-model="type" :localdata="range"></uni-data-select>
			</view>
			<view class="issue" @click="issue">
				<button type="default" size="mini" style="color:#fff;backgroundColor:#008676;">发表</button>
			</view>
		</view>

		<view class="content">
			<textarea v-model="content" auto-height placeholder="这一刻的想法..." />
		</view>
		<view class="imgs">
			<uni-file-picker fileMediatype="image" mode="grid" limit="9" :auto-upload="false"
				@select="handleSelect" @delete="handleDelete" @success="success" />
		</view>
	</view>
</template>

<script>
	import { toRaw } from 'vue'
	export default {
		data() {
			return {
				imgs: [],
				content: '',
				type: 0,
				
				range: [
					{ value: 0, text: "表白墙" },
					{ value: 1, text: "二手交易" },
					{ value: 2, text: "寻物" },
				],
			}
		},
		onLoad(option) {
			this.type = option.type == undefined ? 0 : parseInt(option.type)
			console.log(this.type);
		},
		methods: {
			issue() {
				if (this.content.length == 0 && this.imgs.length == 0) {
					uni.showToast({
						title: '内容不能为空',
						duration: 2000,
						icon: 'none'
					})
					return 
				}
				this.$request.post('/mini/forum/issue', {
					type: this.type,
					content: this.content,
					imgs: this.imgs
				}).then(res => {
					if (res.code === 200) {
						uni.navigateBack()
						// uni.redirectTo({ url: '/pages/forum/forum?type=' + this.type })
					} else {
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},
			
			handleSelect(res) {
				for (let tempImg of res.tempFilePaths) {
					this.uploadImg(tempImg)
				}
			},
			handleDelete(err) {
				const num = this.imgs.findIndex(v => v.tempUrl === err.tempFilePath);
				this.imgs.splice(num, 1);
			},
			uploadImg(tempFilePath) {
				uni.uploadFile({
					url: this.$request.baseUrl + '/common/upload',
					filePath: tempFilePath,
					name: 'file',
					header: {
						'content-type': 'multipart/form-data' 
					},
					success:(res) => {
						res = JSON.parse(res.data)
						if (res.code == 200) {
							this.imgs.push({
								tempUrl: tempFilePath,
								url: res.fileName
							})
						} else {
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon: 'none'
							})
						}
					}
				});
			},
		}
	}
</script>

<style>
	.operate {
		width: 660rpx;
		margin: 0 auto;
		margin-top: 20rpx;
		display: flex;
		justify-content: space-between;
	}
	.operate .type {
		width: 170rpx;
	}

	.content,
	.imgs {
		width: 620rpx;
		margin: 15rpx auto;
	}

	.content textarea {
		width: 100%;
		min-height: 100px;
	}
</style>